package com.glebusheg.ui 
{
	import flash.display.SimpleButton;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;

	/**
	 * @author Gleb Volkov
	 */
	public class UIScrollBar extends ScrollBase 
	{
		private var _forward:SimpleButton;
		private var _backward:SimpleButton;
		private var _slider:UISlider;
		
		private var _lineSize:int = 1; 
		
		public function UIScrollBar()
		{
			// базовые контроллы можно заменить на кастомеые ради красивых эффектов
			_forward = getChildByName("forward") as SimpleButton;
			if (_forward)
				_forward.addEventListener(MouseEvent.MOUSE_DOWN, forwardHandler);
			
			_backward = getChildByName("backward") as SimpleButton; 
			if (_backward)
				_backward.addEventListener(MouseEvent.MOUSE_DOWN, backwardHandler);
			
			var slider:Sprite = getChildByName("slider") as Sprite;
			if(slider)
			{
				_slider = new UISlider(slider);
				_slider.addEventListener(Event.CHANGE, sliderChangeHandler);
			}
			
			resize(height);
		}

		private function sliderChangeHandler(event:Event):void 
		{
			dispatchEvent(event);
		}

		private function forwardHandler(event:MouseEvent):void 
		{
			_slider.value += _lineSize;
			dispatchEvent(new Event(Event.CHANGE));
		}
		
		private function backwardHandler(event:MouseEvent):void 
		{
			_slider.value -= _lineSize;
			dispatchEvent(new Event(Event.CHANGE));
		}
		
		public function resize(value:Number):void
		{
			// check for orient in future
			if (_slider) _slider.resize(value);
			if (_backward) _backward.y = _slider.content.height;
		}
		
		public function destroy():void
		{
			if (_forward)
				_forward.removeEventListener(MouseEvent.MOUSE_DOWN, forwardHandler);
			if (_backward)
				_backward.removeEventListener(MouseEvent.MOUSE_DOWN, backwardHandler);
				
			if (_slider)
			{
				_slider.destroy();
				_slider.removeEventListener(Event.CHANGE, sliderChangeHandler);
				_slider = null;
			}
		}
		
		public function setSliderParams(min:Number, max:Number, value:Number):void
		{
			if(_slider.orientation == UIOrientation.HORIZONTAL)
				_slider.setSliderParams(min, max, value);
			else
				_slider.setSliderParams(max, min, value);
		}

		public function set value(v:Number):void
		{
			_slider.value = v;
		}
		public function get value():Number
		{
			return _slider.value;
		}
		
		public function set lineSize(value:int):void
		{
			_lineSize = value;
		}
		public function get lineSize():int
		{
			return _lineSize;
		}
		
		public function get controlSize():int
		{
			var size:int =  0;
			// TODO: check for orientation
			if (_forward) size = _forward.height;
			if (_backward) size = _backward.height;
			return size;
		}
	}
}